package com.sukaiyi.giteejavaapi.apifetcher;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ZipUtil;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class GetWebDriver {

    private static final String DRIVER_FOLDER = ".drivers";
    private static final String WEB_DRIVER_URL = "https://cdn.npm.taobao.org/dist/chromedriver/84.0.4147.30/chromedriver_win32.zip";
    private static final String RAW_DOWNLOADED = DRIVER_FOLDER + File.separator + "chromedriver_win32.zip";
    private static final String DOWNLOADED_DRIVER_PATH = DRIVER_FOLDER + File.separator + "chromedriver.exe";

    @BeforeAll
    static void ensureFolder() {
        File file = new File(DRIVER_FOLDER);
        if (!file.exists() && !file.mkdirs()) {
            throw new IllegalStateException("folder cannot be created: " + DRIVER_FOLDER);
        }
    }

    @Test
    public void download() {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            URL url = new URL(WEB_DRIVER_URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                os = new FileOutputStream(RAW_DOWNLOADED);
                IoUtil.copy(is, os, 8192);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(is);
            IoUtil.close(os);
            if (connection != null) {
                connection.disconnect();
            }
        }
        File zipFile = new File(RAW_DOWNLOADED);
        File unzipFile = new File(DRIVER_FOLDER);
        ZipUtil.unzip(zipFile, unzipFile);
        FileUtil.del(zipFile);
    }

}
